﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace objass
{
    /// <summary>
    /// Interaction logic for Edit2Window.xaml
    /// </summary>
    public partial class EditNodeWindow : UserControl
    {
        private const string DefaultNodeinfo = "请输入节点的相关内容...";
        private ModifyInfo modifyInfo = new ModifyInfo();
        public EditNodeWindow()
        {
            InitializeComponent();
        }

        public void LoadNodes()
        {
            var app = (App)Application.Current;
            var nodes = app.GetNodeNames();
            // 清空 ListBox
            wordSelector.Items.Clear();
            // 遍历节点列表并添加到 ListBox
            foreach (var node in nodes)
            {
                wordSelector.Items.Add(node);
            }
            labelSaved.Content = $"已保存节点数：{nodes.Count}";
        }

        private void Button_Click_Batch_Add(object sender, RoutedEventArgs e)
        {
            // 创建对话框窗口
            Window dialog = new Window
            {
                Title = "导入一批节点",
                Width = 300,
                Height = 150,
                WindowStartupLocation = WindowStartupLocation.CenterScreen,
                ResizeMode = ResizeMode.NoResize,
                Owner = Application.Current.MainWindow,
            };

            // 创建对话框内容
            StackPanel panel = new StackPanel { Margin = new Thickness(10) };

            Label label = new Label { Content = "请输入一组名字，以逗号间隔" };
            TextBox textBox = new TextBox { Margin = new Thickness(0, 10, 0, 10) };

            StackPanel buttonPanel = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right };
            Button okButton = new Button { Content = "确定", Width = 75, Margin = new Thickness(5, 0, 0, 0) };
            Button cancelButton = new Button { Content = "取消", Width = 75, Margin = new Thickness(5, 0, 0, 0) };

            buttonPanel.Children.Add(okButton);
            buttonPanel.Children.Add(cancelButton);

            panel.Children.Add(label);
            panel.Children.Add(textBox);
            panel.Children.Add(buttonPanel);

            dialog.Content = panel;

            // 定义变量来接受输入框的值
            string inputValue = string.Empty;

            // 处理按钮点击事件
            okButton.Click += (s, args) =>
            {
                // 在这里处理输入框的值
                inputValue = textBox.Text;
                // 关闭对话框
                dialog.DialogResult = true;
                dialog.Close();
            };

            cancelButton.Click += (s, args) =>
            {
                dialog.DialogResult = false;
                dialog.Close();
            };

            // 显示对话框
            if (dialog.ShowDialog() == true)
            {
                var app = (App)Application.Current;
                if (modifyInfo.isModify)
                {
                    app.SaveNode(modifyInfo.Name, TextBoxContent.Text, CheckIsCategory.IsChecked == true);
                }
                app.AddNodes(inputValue);
                LoadNodes();
                LocateNode(inputNode.Text);
                labelSaved.Content = $"已保存节点数：{app.GetNodeNames().Count}"; // 更新已保存节点数
            }
        }

        private void Button_Click_Delete(object sender, RoutedEventArgs e)
        {
            if (wordSelector.SelectedItem == "类别" || wordSelector.SelectedItem == "文档信息")
            {
                MessageBox.Show("不能删除系统节点", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            // 弹出确认对话框
            MessageBoxResult result = MessageBox.Show("真的要删除吗？", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                // 删除所选节点的逻辑
                if (wordSelector.SelectedItem != null)
                {
                    var app = (App)Application.Current;
                    app.DeleteNode(wordSelector.SelectedItem.ToString()); // 删除节点
                    wordSelector.Items.Remove(wordSelector.SelectedItem);
                    modifyInfo.Name = "";
                    modifyInfo.isModify = false;
                    inputNode.Text = "";
                    CheckIsCategory.IsChecked = false;
                    TextBoxContent.Text = DefaultNodeinfo;
                    labelSaved.Content = $"已保存节点数：{app.GetNodeNames().Count}"; // 更新已保存节点数
                }
            }
        }

        void UpdateByNode(string nodeName)
        {
            var app = (App)Application.Current;
            if (modifyInfo.isModify)
            {
                app.SaveNode(modifyInfo.Name, TextBoxContent.Text, CheckIsCategory.IsChecked == true);
            }
            modifyInfo.Name = nodeName;
            modifyInfo.isModify = false;
            CheckIsCategory.IsChecked = app.IsNodeForbidPass(nodeName);
            TextBoxContent.Text = app.GetNodeContent(nodeName);
            if(TextBoxContent.Text == "")
            {
                TextBoxContent.Text = DefaultNodeinfo;
            }
        }

        private void LocateNode(string nodeName)
        {
            for (int i = 0; i < wordSelector.Items.Count; i++)
            {
                if (wordSelector.Items[i].ToString().StartsWith(nodeName))
                {
                    wordSelector.SelectedIndex = i;
                    wordSelector.ScrollIntoView(wordSelector.Items[i]); // 确保选中的项在可视化界面里
                    UpdateByNode(wordSelector.Items[i].ToString());
                    break;
                }
            }
        }

        private void InputNode_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 处理 inputNode 的输入变化事件
            TextBox textBox = sender as TextBox;
            if (textBox != null)
            {
                string newText = textBox.Text;
                // WordSelector根据newText的值，定位到最接近的选项，并选中
                if (newText != string.Empty)
                {
                    LocateNode(newText);
                }
                else
                {
                    wordSelector.SelectedIndex = -1; // 清除选中项
                }
            }
        }

        private void WordSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        }
        private void WordSelector_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            // 处理 wordSelector 的鼠标左键释放事件
            ListBox listBox = sender as ListBox;
            if (listBox != null && listBox.SelectedItem != null)
            {
                string selectedItem = listBox.SelectedItem.ToString();
                inputNode.Text = selectedItem;
                UpdateByNode(inputNode.Text);
            }
        }

        private void CheckIsCategory_Checked(object sender, RoutedEventArgs e)
        {
            modifyInfo.isModify = true;
        }

        private void CheckIsCategory_Unchecked(object sender, RoutedEventArgs e)
        {
            modifyInfo.isModify = true;
        }
        private void TextBoxContent_TextChanged(object sender, TextChangedEventArgs e)
        {
            modifyInfo.isModify = true;
        }

        private void EditNodeWindow_Unloaded(object sender, RoutedEventArgs e)
        {
            // 处理窗口关闭或销毁事件
            var app = (App)Application.Current;
            if (modifyInfo.isModify)
            {
                app.SaveNode(modifyInfo.Name, TextBoxContent.Text, CheckIsCategory.IsChecked == true);
            }
        }

        private void Button_Click_ClipBoard_Add(object sender, RoutedEventArgs e)
        {
            var dialog = new ClipBoardInput();
            dialog.Owner = Application.Current.MainWindow;
            dialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            dialog.ResizeMode = ResizeMode.NoResize;
            dialog.Title = "从剪贴板导入节点";
            dialog.ShowDialog();
            if (dialog.DialogResult == true)
            {
                var app = (App)Application.Current;
                if (modifyInfo.isModify)
                {
                    app.SaveNode(modifyInfo.Name, TextBoxContent.Text, CheckIsCategory.IsChecked == true);
                }
                app.AddNodes(dialog.ClipboardText);
                LoadNodes();
                LocateNode(inputNode.Text);
                labelSaved.Content = $"已保存节点数：{app.GetNodeNames().Count}"; // 更新已保存节点数
            }
        }

        private void Button_Click_Change_Node(object sender, RoutedEventArgs e)
        {
            // 创建对话框窗口
            Window dialog = new Window
            {
                Title = "更改节点名字",
                Width = 300,
                Height = 200,
                WindowStartupLocation = WindowStartupLocation.CenterScreen,
                ResizeMode = ResizeMode.NoResize,
                //Owner = this, // 指定父窗口为 Edit2Rel
            };

            var app = (App)Application.Current;
            // 创建对话框内容
            StackPanel panel = new StackPanel { Margin = new Thickness(10) };

            System.Windows.Controls.Label label1 = new System.Windows.Controls.Label { Content = "输入原名字" };
            TextBox textBox1 = new TextBox { Margin = new Thickness(0, 10, 0, 10) };
            System.Windows.Controls.Label label2 = new System.Windows.Controls.Label { Content = "输入新名字" };
            TextBox textBox2 = new TextBox { Margin = new Thickness(0, 10, 0, 10) };

            StackPanel buttonPanel = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right };
            Button okButton = new Button { Content = "确定", Width = 75, Margin = new Thickness(5, 0, 0, 0) };
            Button cancelButton = new Button { Content = "取消", Width = 75, Margin = new Thickness(5, 0, 0, 0) };

            buttonPanel.Children.Add(okButton);
            buttonPanel.Children.Add(cancelButton);

            panel.Children.Add(label1);
            panel.Children.Add(textBox1);
            panel.Children.Add(label2);
            panel.Children.Add(textBox2);
            panel.Children.Add(buttonPanel);

            dialog.Content = panel;

            // 定义变量来接受输入框的值
            string nodeName = string.Empty;
            string newName= string.Empty;

            // 处理按钮点击事件
            okButton.Click += (s, args) =>
            {
                // 在这里处理输入框的值
                nodeName = textBox1.Text;
                newName = textBox2.Text;
                if (!string.IsNullOrEmpty(nodeName) && !string.IsNullOrEmpty(newName))
                {
                    //if(app.IsNodeExist(newName))
                    //{
                    //    MessageBox.Show("新名字已存在", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    //    return;
                    //}

                    // 关闭对话框
                    dialog.DialogResult = true;
                    dialog.Close();
                }
                else
                {
                    MessageBox.Show("请输入有效的名称", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            };

            cancelButton.Click += (s, args) =>
            {
                dialog.DialogResult = false;
                dialog.Close();
            };

            // 显示对话框
            if (dialog.ShowDialog() == true)
            {
                app.ChangeNodeName(nodeName, newName);
                LoadNodes();
                LocateNode(inputNode.Text);
            }
        }
    }
    public class ModifyInfo
    {
        public ModifyInfo()
        {
            Name = "";
            isModify = false;
        }

        public string Name { get; set; }
        public bool isModify { get; set; }
    }
}
